// var blockCount = 4;
var blockCount = location.search.split('blocks=')[1] ? location.search.split('blocks=')[1] : 3;

var firstBlockSprite;
var secondBlockSprite;
var thirdBlockSprite;

var firstTowerSprite;
var secondTowerSprite;
var thirdTowerSprite;

var firstBaseSprite;
var secondBaseSprite;
var thirdBaseSprite;

var firstTowerRect;
var secondTowerRect;
var thirdTowerRect;

var brickPickedUp = false;
var currentlyPickedUpEntry;

var firstTowerArray;
var secondTowerArray;
var thirdTowerArray;

var TowerOfHanoiLayer;
var gameOverLabel;

var performGameOver = function(layer) {
    cc.eventManager.removeAllListeners(); // Disable input listener.

    cc.audioEngine.playEffect(res.victory_ogg);

    var destinationPoint = gameOverLabel.getPosition();
    destinationPoint.y = cc.director.getWinSize().height/2;

    /* Apply animation for the label */
    gameOverLabel.runAction(
        cc.Spawn.create(
            cc.MoveTo.create(0.3, destinationPoint),
            cc.TintTo.create(2.5,255,125,0)
        )
    );

    console.log("Game over.");
}

var pickUpBlock = function(block) {
    var destinationPoint = block.getPosition();
    destinationPoint.y = firstTowerRect.y + firstTowerRect.height/2 + block.getBoundingBox().height/2;

    block.runAction(
        cc.MoveTo.create(0.3, destinationPoint)
    );

    brickPickedUp = true;
}

var pickUpBlockFromColumn = function(column) {
    var targetArray;

    switch (column) {
        case 1:
            targetArray = firstTowerArray;
            break;
        case 2:
            targetArray = secondTowerArray;
            break;
        case 3:
            targetArray = thirdTowerArray;
            break;
        default:
            return;
            break;
    }

    var blocksBelowCount = targetArray.length;

    if (blocksBelowCount > 0) {
        currentlyPickedUpEntry = targetArray.pop();

        pickUpBlock(currentlyPickedUpEntry);

        cc.audioEngine.playEffect(res.pick_up_ogg);

        var logMessage = "Picked up " + currentlyPickedUpEntry + " from column " + column;
        console.log(logMessage);
    }
}

var putDownBlockToColumn = function(block, column) {
    if (currentlyPickedUpEntry == null) {
        return;
    }

    var targetArray;

    switch (column) {
        case 1:
            targetArray = firstTowerArray;
            break;
        case 2:
            targetArray = secondTowerArray;
            break;
        case 3:
            targetArray = thirdTowerArray;
            break;
    }

    var blocksBelowCount = targetArray.length;

    if (blocksBelowCount > 0) {
        var lastBlockIndex = targetArray.length - 1;
        var lastBlock = targetArray[lastBlockIndex];

        if (lastBlock.getBoundingBox().width < currentlyPickedUpEntry.getBoundingBox().width) {
            return;
        }
    }

    targetArray.push(currentlyPickedUpEntry);

    var logMessage = "Pushed " + currentlyPickedUpEntry + " to " + column + " array.";
    console.log(logMessage);
    
    var destinationPoint = currentlyPickedUpEntry.getPosition();
    destinationPoint.y = firstBaseSprite.y + firstBaseSprite.height + currentlyPickedUpEntry.getBoundingBox().height * blocksBelowCount - 1;

    currentlyPickedUpEntry.runAction(
        cc.MoveTo.create(0.3, destinationPoint)
    );

    currentlyPickedUpEntry = null;
    brickPickedUp = false;

    cc.audioEngine.playEffect(res.put_down_ogg);

    if ((column == 3) && (blocksBelowCount == (blockCount-1))) {
        performGameOver(TowerOfHanoiLayer);
    }
}

var moveBlockToColumn = function(block, column) {
    var destinationPoint = block.getPosition();

    switch (column) {
        case 1:
            destinationPoint.x = firstBaseSprite.x;
            break;
        case 2:
            destinationPoint.x = secondBaseSprite.x;
            break;
        case 3:
            destinationPoint.x = thirdBaseSprite.x;
            break;
    }

    block.runAction(
        cc.MoveTo.create(0.3, destinationPoint)
    );

    cc.audioEngine.playEffect(res.move_ogg);
}

TowerOfHanoiLayer = cc.Layer.extend({
    ctor : function(){
        //1. call super class's ctor function
        this._super();
    },
    init:function(){
        this._super(); //call super class's super function

        var winsize = cc.director.getWinSize(); // get the screen size of your game canvas
        var centerpos = cc.p(winsize.width / 2, winsize.height / 2); // calculate the center point

        var towerHeightScale = 25;

        var backgroundSprite = cc.Sprite.create(res.background_image_jpg, new cc.Rect(0, 0, winsize.width, winsize.height));
        backgroundSprite.setPosition(centerpos);
        this.addChild(backgroundSprite);

        /* create a tower base images and set it's position at the center of the screen */
        firstBaseSprite = cc.Sprite.create(res.block_image_png);
        firstBaseSprite.setScale(1, 1);
        firstBaseSprite.setPosition(cc.p(winsize.width / 6, 10));
        this.addChild(firstBaseSprite);

        firstTowerSprite = cc.Sprite.create(res.tower_image_png);
        firstTowerSprite.setScale(1, 1);
        firstTowerSprite.setPosition(cc.p(winsize.width / 6, 10));
        this.addChild(firstTowerSprite);

        secondBaseSprite = cc.Sprite.create(res.block_image_png);
        secondBaseSprite.setScale(1, 1);
        secondBaseSprite.setPosition(cc.p(winsize.width / 6 + winsize.width / 6 * 2, 10));
        this.addChild(secondBaseSprite);

        secondTowerSprite = cc.Sprite.create(res.tower_image_png);
        secondTowerSprite.setScale(1, 1);
        secondTowerSprite.setPosition(cc.p(winsize.width / 6 + winsize.width / 6 * 2, 10));
        this.addChild(secondTowerSprite);

        thirdBaseSprite = cc.Sprite.create(res.block_image_png);
        thirdBaseSprite.setScale(1, 1);
        thirdBaseSprite.setPosition(cc.p(winsize.width / 6 + winsize.width / 6 * 4, 10));
        this.addChild(thirdBaseSprite);

        thirdTowerSprite = cc.Sprite.create(res.tower_image_png);
        thirdTowerSprite.setScale(1, 1);
        thirdTowerSprite.setPosition(cc.p(winsize.width / 6 + winsize.width / 6 * 4, 10));
        this.addChild(thirdTowerSprite);

        /* Init data arrays */
        firstTowerArray = [];
        secondTowerArray = [];
        thirdTowerArray = [];

        /* Validate user input value */
        if (blockCount < 3) {
            blockCount = 3;
        }
        else if (blockCount > 10) {
            blockCount = 10;
        }

        /* Create blocks that should move */
        var previousBlockWidthScale = 1;

        for (var iterator = 0; iterator < blockCount; iterator++) {
            var blockSprite = cc.Sprite.create(res.block_image_png);

            previousBlockWidthScale = previousBlockWidthScale * 0.9;

            blockSprite.setScale(previousBlockWidthScale, 1);
            blockSprite.setPosition(cc.p(winsize.width / 6, 10+(blockSprite.getContentSize().height)*(iterator+1)-1));
            this.addChild(blockSprite);

            firstTowerArray.push(blockSprite);
        }

        /* Declare rects that will be used for inspecting mouse clicks */
        firstTowerRect = firstBaseSprite.getBoundingBox();
        firstTowerRect.y = firstTowerSprite.getPosition().y;
        firstTowerRect.height += firstTowerSprite.getBoundingBox().height;

        secondTowerRect = secondBaseSprite.getBoundingBox();
        secondTowerRect.y = secondTowerSprite.getPosition().y;
        secondTowerRect.height += secondTowerSprite.getBoundingBox().height;

        thirdTowerRect = thirdBaseSprite.getBoundingBox();
        thirdTowerRect.y = thirdTowerSprite.getPosition().y;
        thirdTowerRect.height += thirdTowerSprite.getBoundingBox().height;

        /* Init "Game Over" label */
        gameOverLabel = cc.LabelTTF.create("Game Over", "Tahoma", 38);
        gameOverLabel.x = winsize.width / 2;
        gameOverLabel.y = -gameOverLabel.getBoundingBox().height;
        this.addChild(gameOverLabel);


        /* Add mouse listener */
        cc.eventManager.addListener({
            event: cc.EventListener.MOUSE,
            onMouseMove: function(event){
                // var str = "MousePosition X: " + event.getLocationX() + "  Y:" + event.getLocationY();
                // console.log(str);
            },
            onMouseUp: function(event){
                var str = "Mouse Up detected, Key: " + event.getButton();
                console.log(str);
            },
            onMouseDown: function(event){
                var str = "Mouse Down detected, Key: " + event.getButton();
                console.log(str);

                /* Determine click location */                
                var firstTowerClicked = cc.rectContainsPoint(firstTowerRect, event.getLocation());
                var secondTowerClicked = cc.rectContainsPoint(secondTowerRect, event.getLocation());
                var thirdTowerClicked = cc.rectContainsPoint(thirdTowerRect, event.getLocation());

                /* Declare temporary parameters */
                var clickedTowerNumber;
                var destinationBaseSprite;

                /* Init temporary parameters */
                if (firstTowerClicked == true) {
                    clickedTowerNumber = 1;
                    destinationBaseSprite = firstBaseSprite;
                }
                else if (secondTowerClicked == true) {
                    clickedTowerNumber = 2;
                    destinationBaseSprite = secondBaseSprite;
                }
                else if (thirdTowerClicked == true) {
                    clickedTowerNumber = 3;
                    destinationBaseSprite = thirdBaseSprite;
                }

                if (brickPickedUp == false) {
                    pickUpBlockFromColumn(clickedTowerNumber);
                }
                else {
                    var destinationPoint = currentlyPickedUpEntry.getPosition();
                    destinationPoint.x = destinationBaseSprite.x;

                    if (Math.round(currentlyPickedUpEntry.getPosition().x) == Math.round(destinationPoint.x)) {
                        putDownBlockToColumn(currentlyPickedUpEntry, clickedTowerNumber);
                    }
                    else {
                        moveBlockToColumn(currentlyPickedUpEntry, clickedTowerNumber);
                    }
                }
            },
            onMouseScroll: function(event){
                var str = "Mouse Scroll detected, X: " + event.getLocationX() + "  Y:" + event.getLocationY();
                console.log(str);
            }
        },this);
    }
});

var TowerOfHanoiScene = cc.Scene.extend({
    onEnter:function() {
        this._super();

        var layer = new TowerOfHanoiLayer();
        layer.init();
        this.addChild(layer);
    }
});